<script lang="ts" setup>
  import { CaretBottom } from '@element-plus/icons-vue'
  import appStore from '@/store'
  import userService from '@/api/userService'
  import { useRouter, useRoute } from 'vue-router'
  import regions from '../tips/regions.json'
  import { reactive, ref, onUnmounted, watch } from 'vue'
  import VueCookies from 'vue-cookies'
  import { useI18n } from 'vue-i18n'
  import { ElMessageBox } from 'element-plus'
  import mitt from '@/utils/mitt'
  import { nextTick } from 'vue'
  const cookie: any = VueCookies
  const router = useRouter()
  const route = useRoute()
  const routeName = route.name as string
  let regionExist = ref(['createFleet'].includes(routeName))
  let UserType = ref('0')
  const regionData: { [key: string]: string } = reactive(regions)
  interface optionList {
    value: string
    label: string
  }
  const regionOptions: optionList[] = reactive([])
  const regionValue = ref('')
  let origins: { [key: string]: { [key: string]: any } } = reactive({ data: {} })
  const logOut = async () => {
    let res = await userService.logout()
    if (res.status == 204) {
      cookie.remove('ExpireTime')
      appStore.userStore.$reset()
      localStorage.clear()
      router.push({ name: 'Login' })
    }
  }
  const toUserInfo = () => {
    router.push({ name: 'userInfoList' })
  }
  const getOrigininfo = async () => {
    let res = await userService.getOrigininfo(appStore.userStore.name, regionValue.value)
    if (res.status === 200) {
      if (res.data.origins) {
        origins.data = JSON.parse(JSON.stringify(res.data.origins))
        let dataList = ref(origins.data[0])
        let projectId = localStorage.getItem('project_id')
        let oriprojectId = localStorage.getItem('ori_project_id')
        origins.data.forEach((item: any) => {
          if (item.ori_project_id == projectId && item.project_id == oriprojectId) {
            dataList.value = item
          }
        })
        localStorage.setItem('project_id', dataList.value.ori_project_id)
        appStore.userStore.updateProject_id(dataList.value.ori_project_id)
        localStorage.setItem('ori_project_id', dataList.value.project_id)
        appStore.userStore.oriProject_id(dataList.value.project_id)
        appStore.userStore.updateOrigin(dataList.value.domain_name)
        appStore.userStore.updateRegion(regionValue.value)
      }
    }

    nextTick(() => {
      appStore.userStore.updateChangeId(false)
    })
    UserType.value = localStorage.getItem('UserType') as string
    if (!appStore.userStore.project_id && UserType.value != '9') {
      ElMessageBox.alert('您没有关联资源租户，没有权限查看，请联系管理员', {
        confirmButtonText: '请登出',
        callback: () => {
          logOut()
        }
      })
    }
  }
  const getRegion = async () => {
    let res = await userService.getRegion()
    let regionArr = res.data.regions
    if (regionArr.length) {
      regionArr.forEach((element: any, index: any) => {
        regionOptions.length = 0
        regionOptions.push({
          value: regionArr[index],
          label: regionData[element]
        })
      })
      regionValue.value = regionArr[0]
      localStorage.setItem('region', regionValue.value)
    }
    appStore.userStore.updateChangeId(true)
    getOrigininfo()
  }

  const changeorigin = (obj: any) => {
    let project_id = obj.ori_project_id
    let ori_project_id = obj.project_id
    localStorage.setItem('project_id', project_id)
    localStorage.setItem('ori_project_id', ori_project_id)
    appStore.userStore.updateProject_id(project_id)
    appStore.userStore.oriProject_id(ori_project_id)
    appStore.userStore.updateOrigin(obj.domain_name)
    appStore.userStore.updateChangeId(true)
    localStorage.setItem('region', regionValue.value)
    appStore.userStore.updateRegion(regionValue.value)
    nextTick(() => {
      appStore.userStore.updateChangeId(false)
    })
  }
  getRegion()
  mitt.on('getRegion', getRegion)
  onUnmounted(() => {
    mitt.off('getRegion', getRegion)
  })

  watch(
    () => router.currentRoute.value,
    async () => {
      await router.isReady()
      let routeName = route.name as string
      regionExist.value = ['createFleet'].includes(routeName)
    }
  )
</script>
<template>
  <div id="meta-header">
    <div class="header-left">
      <div class="header-box">
        <img src="@/assets/images/GameFlexMatch-logo.png" alt="" />
      </div>
      <div class="region-box" v-if="!regionExist">
        <div class="region-label">区域:</div>
        <div class="run-select">
          <el-select v-model="regionValue" placeholder="请选择region">
            <el-option v-for="item in regionOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
    </div>
    <div class="header-right">
      <div>
        <div v-if="UserType === '9'" class="manage">{{ '超级管理员' }}</div>
        <div v-else-if="UserType === '0'" class="hedaer-rank">{{ '用户' }}</div>
        <div v-else class="manage">{{ '普通管理员' }}</div>
      </div>
      <div class="header-user">
        <el-dropdown @command="changeorigin" popper-class="originDrop">
          <span class="el-dropdown-link">
            {{ appStore.userStore.name || '--' }}
            <el-icon class="el-icon--right">
              <CaretBottom />
            </el-icon>
          </span>
          <template #dropdown>
            <div class="user-dtitle">
              <div class="dtitle-line"></div>
              租户名称/项目ID
            </div>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(item, key) in origins.data"
                :key="key"
                :command="item"
                :class="item.domain_name === appStore.userStore.origin_domain_name && item.project_id === appStore.userStore.ori_project_id ? 'active' : ''"
              >
                <div class="originDrop-name">{{ item.domain_name }}</div>
                <div class="originDrop-id">{{ item.project_id }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
            <div class="user-dbottom">
              <div class="user-dbottom-item" @click="toUserInfo">账号信息</div>
              <div class="user-dbottom-item" @click="logOut">登出</div>
            </div>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  #meta-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 49px;
    padding: 0 40px 0 20px;
    background-color: $blank-color;
    border-bottom: 1px solid $border-color;
    color: $text-color;

    .header-left {
      display: flex;
      align-items: center;

      .header-box {
        img {
          margin: 0 -30px 0 -50px;
          height: 37px;
          width: 270px;
          transform: scale(0.65);
        }
      }

      .region-box {
        display: flex;
        align-items: center;
        margin-left: 40px;

        .region-label {
          margin-right: 16px;
        }

        .el-select {
          width: 140px;
        }
      }

      .header-icon {
        width: 20px;
        height: 20px;
        margin-right: 10px;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      font-size: 14px;

      .hedaer-rank {
        text-align: center;
        line-height: 18px;
        height: 18px;
        background-color: $main-color;
        width: 52px;
        color: $blank-color;
        border-radius: 4px;
        margin-right: 8px;
      }

      .manage {
        text-align: center;
        line-height: 18px;
        height: 18px;
        width: 80px;
        color: $blank-color;
        border-radius: 4px;
        margin-right: 8px;
        background-color: #ff4747;
      }

      .el-dropdown {
        color: $text-color;
        align-items: center;
        height: 18px;
      }

      :global(.user-dtitle) {
        height: 50px;
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #8a8e99;
        padding: 0 16px;
      }

      :global(.dtitle-line) {
        width: 2px;
        height: 14px;
        background: #325cb0;
        margin-right: 8px;
      }

      :global(.user-dbottom) {
        height: 90px;
        border-top: 1px solid $border-color;
      }

      :global(.user-dbottom-item) {
        height: 45px;
        display: flex;
        align-items: center;
        padding: 0 16px;
        cursor: pointer;
        font-size: 14px;
      }

      :global(.user-dbottom-item:hover) {
        color: $main-color;
      }
    }
  }
  :deep(.active) {
    color: #325cb0 !important;
    border-right: 3px solid #325cb0;
  }
</style>
